import got from 'got';
import * as cheerio from 'cheerio';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filenameNew = fileURLToPath(import.meta.url);
const __dirnameNew = path.dirname(__filenameNew);

export const poetry = {
    getPoetryList() {
        return got('https://www.cngwzj.com/tangshi300/78.html').then(({ body }) => {
            const $ = cheerio.load(body);
            let r = [];
            $('.tj_listbox .tj_main a').each((_, a) => {
                let href = $(a).attr('href');
                let title = $(a).text();
                r.push({ href, title });
            });
            return r;
        });
    },
    getPoetryContent(url) {
        return got.get(url).then(({ body }) => {
            const $ = cheerio.load(body);
            return $('.strbox .t-l').eq(0).html();
        });
    },
    getPoetry() {
        return this.getPoetryList().then(list => {
            let r = [];
            return list.reduce((a, b, index) => {
                return a.then(() => {
                    let { title, href } = b;
                    return new Promise(resolve => {
                        setTimeout(() => {
                            console.log('---->', index, title);
                            this.getPoetryContent(href).then(content => {
                                r.push({ title, href, content });
                                resolve();
                            });
                        }, 2000);
                    });
                });
            }, Promise.resolve()).then(() => {
                console.log(r);

                fs.writeFileSync(path.resolve(__dirnameNew, './../source/poetry.json'), JSON.stringify(r));
                return r;
            });
        });
    },
    getPoetryDetail() {
        let content = fs.readFileSync(path.resolve(__dirnameNew, './../source/poetry.json'));
        let list = JSON.parse(content);

        return list.reduce((a, item, index) => {
            return a.then(() => {
                let url = item.href.replace('pygushi', 'gushi');
                console.log('-----', index, item.title);
                return new Promise(resolve => {
                    setTimeout(() => {
                        return got(url).then(({ body }) => {
                            const $ = cheerio.load(body);
                            item.notes = $('.strbox.t-l.mb-10').html().trim();
                            let mm = [];
                            $('.tj_item .text').each((_, a) => {
                                let title = $(a).find(".tj_title").text().trim();
                                let content = $(a).find('.tj_main').html().trim();
                                mm.push({ title, content });
                            });
                            item.detai = mm;
                            fs.writeFileSync(path.resolve(__dirnameNew, './../source/poetry.json'), JSON.stringify(list));
                            resolve();
                        });
                    }, 2000);
                });
            });
        }, Promise.resolve());
    },
    formatPoetry() {
        let content = fs.readFileSync(path.resolve(__dirnameNew, './../source/poetry.json'));
        let list = JSON.parse(content);

        // list = [list[0]];

        list = list.map(item => {
            let r = [];
            let $ = cheerio.load(item.content);
            $('li').each((_, a) => {
                let line = [];
                $(a).find('span').each((_, b) => {
                    let [pin, word] = $(b).html().split('<br>');
                    word = $(b).html(word).text().trim();
                    line.push({ pin: pin.trim(), word, dot: pin.trim() == '' });
                });
                r.push(line);
            });
            let m = r.map(a => {
                return a.map(b => b.word).join('');
            });
            m.shift();
            let [n, t] = m.shift().split(']');
            item.author = t;
            item.time = n.substring(1);
            item.words = m.join('\n');
            item.content = r;

            $ = cheerio.load('<div id="toptop">' + item.notes + "</div>");

            item.notes = $("#toptop").text().trim();

            item.detai = item.detai.map(({ title, content }) => {
                content = content.replace(/<br>/g, '(||||)');
                let mt = cheerio.load(content).text().trim().split('(||||)').filter(a => a != "").map(a => a.trim().replace(/\n/g, '').replace(/\r/g, '').replace(/[\s]+/g, ''));
                return {
                    title: title.replace('：', ''),
                    items: mt
                };
            });
            return item;
        });
        fs.writeFileSync(path.resolve(__dirnameNew, './../source/poetryClean.json'), JSON.stringify(list));
    }
};